package com.fruit.service.order.impl;

import java.util.concurrent.LinkedTransferQueue;
import org.springframework.stereotype.Service;

import com.fruit.pojo.queue.QueueParams;
import com.fruit.service.order.QueueHandel;

import lombok.extern.slf4j.Slf4j;

/**
 * 队列监听 修改时间：2016.07.15
 */
@Slf4j
@Service
public class QueueService implements QueueHandel {

	private boolean start;
	private OnQueueListener listener;
	/**
	 * 同步队列
	 */
	private LinkedTransferQueue<QueueParams> synQueue = new LinkedTransferQueue<QueueParams>();
	/**
	 * 异步队列
	 */
	private LinkedTransferQueue<QueueParams> asynQueue = new LinkedTransferQueue<QueueParams>();

	@Override
	public void start(OnQueueListener listener) {
		if (start) {
			return;
		}
		start = true;
		this.listener = listener;
		new Thread(new Runnable() {
			public void run() {
				try {
					log.info("queue同步队列开启");
					while (true) {
						QueueParams params = synQueue.take();
						if (QueueService.this.listener != null) {
							QueueService.this.listener.onSynQueueArrived(params);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

		new Thread(new Runnable() {
			public void run() {
				try {
					log.info("queue异步队列开启");
					while (true) {
						QueueParams params = asynQueue.take();
						if (QueueService.this.listener != null) {
							QueueService.this.listener.onAsynQueueArrived(params);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void add(QueueParams params, boolean isAsyn) {
		if (isAsyn) {
			asynQueue.put(params);
		} else {
			synQueue.put(params);
		}
	}

	public boolean remove(QueueParams params, boolean isAsyn) {
		if (isAsyn) {
			return asynQueue.remove(params);
		} else {
			return synQueue.remove(params);
		}
	}

	public int getSize(boolean isAsyn) {
		if (isAsyn) {
			return asynQueue.size();
		} else {
			return synQueue.size();
		}
	}

}
